package com.daiyang.javabasics.demo1;

import java.util.Arrays;
import java.util.HashMap;

public class Test {
    public static void main(String[] args) {
       int [] nums = {1,2,3,2,2};
       totalFruit(nums);


    }
    public static int triangleNumber(int[] nums) {
        Arrays.sort(nums);
        int count =0;
        for(int i=nums.length-1;i>0;i--) {
            int left=0;
            int right=i-1;
            while(right>left) {
                if(nums[left]+nums[right]>nums[i]) {
                    count+=right-left;
                    break;
                } else {
                    left++;
                }
            }
        }
        return count;
    }
    public static int trap(int[] height) {
        int left=0;
        int right=height.length-1;
        int heightright=height[right];
        int heightleft=height[left];
        int cap=0;
        while(left<=right) {
            if(heightleft<heightright) {
                int x=heightleft-height[left];
                if(x>0) {
                    cap+=x;
                }
                heightleft=Math.max(heightleft,height[left]);
                left++;
            } else {
                int x=heightright-height[right];
                if(x>0) {
                    cap+=x;
                }
                heightright=Math.max(heightright,height[right]);
                right--;
            }
        }
        return cap;
    }
    public static int totalFruit(int[] fruits) {
        HashMap<Integer,Integer> hash=new HashMap();
        int left=0,right=0;
        int len=-1;
        while(right<fruits.length) {
            if(hash.containsKey(fruits[right])) {
                Integer x=hash.get(fruits[right]);
                x++;
                hash.put(fruits[right],x);
            }  else {
                hash.put(fruits[right],1);
            }

            while(hash.size()>2) {
                len=Math.max(len,right-left);
                Integer x=hash.get(fruits[left]);
                x--;
                if(x==0) {
                    hash.remove(fruits[left]);
                } else {
                    hash.put(fruits[left],x);
                }
                left++;
            }
            right++;
        }
        return len==-1?fruits.length:len;
    }
}
